import Vue from 'vue'
import Router from 'vue-router'
import login from '../components/login.vue'
import home from '../views/home.vue'

Vue.use(Router)
const router = new Router({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: login },
    { path: '/home', component: home }
  ]
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转过来
  // next() 放行

  // 如果访问的是登录页面，直接放行
  if (to.path === '/login') return next()

  const token = sessionStorage.getItem('token')
  if (token) { // 有token 直接放行
    return next()
  } else { // 无token 跳转到登录页
    router.push('/login')
  }
})
export default router